package me.shurufa.controller;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;


import java.io.File;

import cn.finalteam.okhttpfinal.FileDownloadCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.service.DownloadService;
import me.shurufa.utils.Utils;
import me.shurufa.widget.simpledialog.SimpleDialog;
import okhttp3.Request;

/**
 * Author : andy
 * Date   : 16/4/10 00:51
 * Email  : andyxialm@gmail.com
 * Github : github.com/andyxialm
 * <p/>
 * Description : 版本更新
 */
public class CheckUpdateController {

    private Activity mActivity;
    private SimpleDialog mSimpleDialog;
    private ProgressDialog pd;
    private DialogOnKeyListener mOnKeyListener;

    public CheckUpdateController(Activity activity) {
        mActivity = activity;
        mOnKeyListener = new DialogOnKeyListener();
    }

    /**
     * 强制更新
     */
    public void forceUpdate(final String downloadUrl, final String newVersion, final String description) {
        mSimpleDialog = new SimpleDialog(mActivity);
        mSimpleDialog.setAnimationEnable(true);
        mSimpleDialog.setTitleVisibility(View.VISIBLE);
        mSimpleDialog.setTitleText(String.format(mActivity.getString(R.string.update_new_version), newVersion));
        mSimpleDialog.setContentText(description);
        mSimpleDialog.setContentTextGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
        mSimpleDialog.setNegativeButtonVisibility(View.GONE);
        mSimpleDialog.setCanceledOnTouchOutside(false);
        mSimpleDialog.setOnPositiveListener(mActivity.getString(R.string.update), new SimpleDialog.OnPositiveListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();
                downloadApk(downloadUrl);
            }
        });
        mSimpleDialog.setOnKeyListener(mOnKeyListener);
        mSimpleDialog.show();
    }

    /**
     * 需要更新 但是非强制更新
     */
    public void needUpdate(final String downloadUrl, final String newVersion, final String description) {
        // Settings.setNewVersion(newVersion);
        // 若忽略更新 则不提示升级
        /* if (Settings.getIgnoreUpdate()) {
            return;
        }*/
        mSimpleDialog = new SimpleDialog(mActivity);
        mSimpleDialog.setAnimationEnable(true);
        mSimpleDialog.setTitleVisibility(View.VISIBLE);
        mSimpleDialog.setTitleText(String.format(mActivity.getString(R.string.update_new_version), newVersion));
        mSimpleDialog.setContentText(description);
        mSimpleDialog.setContentTextGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
        mSimpleDialog.setCanceledOnTouchOutside(false);
        mSimpleDialog.setOnPositiveListener(mActivity.getString(R.string.update), new SimpleDialog.OnPositiveListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();

                if (!TextUtils.isEmpty(downloadUrl)) {
                    Utils.showToast(R.string.sys_err);
                    return;
                }
                DownloadService.initDownloadUrl(downloadUrl);
                // DownloadService.initDownloadUrl("http://p.gdown.baidu.com/3501ee038a9062545855f572d88e34ed13809f8c37646b6b5122ef3cd33661c60de8efdae824a2d1e56c7e2a88930ef40602a4528c1c1a00a16e6e65cdb91028276a01c63802b98c484bf5f6199250b4d1ccc991c1006a5f8e90f5258547ded7");
                mActivity.startService(new Intent(mActivity, DownloadService.class));
            }
        });
        mSimpleDialog.setOnNegativeListener(mActivity.getString(R.string.cancel), new SimpleDialog.OnNegativeListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                // Settings.setIgnoreUpdate(true);
                dialog.dismiss();
            }
        });
        mSimpleDialog.show();
    }

    private String getHandleDesc(String description) {
        if (!TextUtils.isEmpty(description)) {
            return "\n" + description;
        }
        return "";
    }

    /**
     * 设置界面 点击非强制更新时
     * @param downloadUrl
     * @param newVersion
     */
    public void settingsNeedUpdate(final String downloadUrl, final String newVersion, final String description) {
        // Settings.setIgnoreUpdate(false);
        needUpdate(downloadUrl, newVersion, description);
    }

    private void downloadApk(String downloadUrl) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return;
        }

        pd = new ProgressDialog(mActivity);
        pd.setTitle(mActivity.getString(R.string.update));
        pd.setMessage("正在下载...");
        pd.setCancelable(false);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMax(100);
        pd.show();

        // OkHttpUtils.get().url("http://p.gdown.baidu.com/3501ee038a9062545855f572d88e34ed13809f8c37646b6b5122ef3cd33661c60de8efdae824a2d1e56c7e2a88930ef40602a4528c1c1a00a16e6e65cdb91028276a01c63802b98c484bf5f6199250b4d1ccc991c1006a5f8e90f5258547ded7")
        /*OkHttpUtils.get().url(downloadUrl)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), System.currentTimeMillis() + "shurufa.apk") {
                    @Override
                    public void inProgress(float progress) {
                        pd.setProgress((int) (100 * progress));
                    }

                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(File file) {
                        installApk(file);
                        pd.dismiss();
                    }
                });*/

        final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + System.currentTimeMillis() + "shurufa.apk");
        HttpRequest.download(downloadUrl, file, new FileDownloadCallback() {
            @Override
            public void onProgress(int progress, long networkSpeed) {
                super.onProgress(progress, networkSpeed);
                pd.setProgress(progress);
            }

            @Override
            public void onDone() {
                super.onDone();
                installApk(file);
                pd.dismiss();
            }
        });
    }

    /**
     * 安装应用
     * @param file
     */
    private void installApk(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        mActivity.startActivity(intent);
    }

    /**
     * 释放资源
     */
    public void release() {
        if (mSimpleDialog != null) {
            mSimpleDialog.dismiss();
            mSimpleDialog = null;
        }

        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    public class DialogOnKeyListener implements DialogInterface.OnKeyListener {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                mSimpleDialog.dismiss();
                mActivity.finish();
            }
            return false;
        }

    }
}
